package com.le.sarrs.service;

import com.google.common.collect.Lists;
import com.le.sarrs.util.Mappings;
import com.le.sarrs.util.HttpToolkit;
import com.le.sarrs.util.StringUtil;
import net.hexi.sword.concurent.AsyncExecutors;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Callable;

@Service
public class SarrsService {

    private static Logger log = LoggerFactory.getLogger(SarrsService.class);

    private static String getVidByPid(String pid) {
        String vid = "";
        String url = "http://127.0.0.1/detail/cbase/q?sk=newmms_vrs_a_" + pid;
        JSONObject json;
        try {
            json = JSONObject.fromObject(HttpToolkit.sendGet(url));
            String isEnd = json.optString("isEnd", "1");
            String vidEpisode = json.optString("vidEpisode", "");
            String[] vidArray = vidEpisode.split(",");
            if (vidArray.length > 0) {
                if ("1".equals(isEnd)) {    //已完结，取第一集vid
                    vid = vidArray[0].split("-")[1];
                } else {    //未完结，取最新一集vid
                    vid = vidArray[vidArray.length - 1].split("-")[1];
                }
            }
        } catch (Exception e) {
            log.error("get vid error! pid: " + pid);
        }

        return vid;
    }

    private static String getVidByFilmPid(String pid) {
        String vid = "";
        String url = "http://127.0.0.1/detail/cbase/q?sk=newmms_vrs_a_" + pid;
        JSONObject json;
        try {
            json = JSONObject.fromObject(HttpToolkit.sendGet(url));
            String vids = json.optString("vids", "");
            String[] vidArray = vids.split(",");
            if (vidArray.length > 0) {
                vid = vidArray[0];
            }
        } catch (Exception e) {
            log.error("get vid error! pid: " + pid);
        }

        return vid;
    }

    /***
     * get detail of others sites
     */
    public static Map<String, JSONObject> getRecommendDetail(String ids, String from) {

        Map<String, JSONObject> idsMap = new HashMap<>();
        String url = "http://127.0.0.1/sarrs?action=getdetail&lc=&id=" + ids
                + "&versiontype=LeJianNews&from=" + from;
        JSONArray jArray = new JSONArray();
        try {
            JSONObject result = JSONObject.fromObject(HttpToolkit.sendGet(url));
            if (result.containsKey("data")) {
                jArray = result.getJSONArray("data");
            }

            for (int i = 0; i < jArray.size(); i++) {
                JSONObject json = jArray.getJSONObject(i);
                JSONObject detail = new JSONObject();
                String name = json.optString("name", "");
                name = StringEscapeUtils.unescapeHtml4(name);
                if (StringUtil.isNotBlank(json.optString("live_id", ""))) {//直播数据
                    detail.put("poster", json.optString("poster", ""));
                    detail.put("begin_time", json.optString("begin_time", ""));
                    detail.put("end_time", json.optString("end_time", ""));
                    detail.put("src", json.optString("src", ""));
                    detail.put("global_id", json.optString("global_id", ""));
                    detail.put("live_id", json.optString("live_id", ""));
                    detail.put("live_status", json.optString("live_status", ""));
                    detail.put("is_big_pic", json.optString("is_big_pic", ""));
                    detail.put("is_pay", json.optString("is_pay", ""));
                    detail.put("name", name);
                    detail.put("rec_source", json.optString("rec_source", ""));
                    detail.put("data_type", "live");
                    detail.put("live_type", json.optString("live_type", ""));
                } else {
                    detail.put("aid", json.optString("aid", ""));
                    detail.put("vid", json.optString("vid", ""));
                    detail.put("category", json.optString("category", ""));
                    detail.put("category_name", json.optString("category_name", ""));
                    detail.put("source_name", json.optString("source_name", ""));
                    detail.put("source", json.optString("source", ""));
                    detail.put("name", name);
                    detail.put("duration", json.optString("duration", ""));
                    detail.put("data_type", "wv");
                    detail.put("mini_poster", json.optString("mini_poster", ""));
                    detail.put("playurl", json.optString("playurl", ""));
                    detail.put("src", json.optString("src", ""));
                    detail.put("play_count", json.optString("play_count", ""));
                    detail.put("poster", json.optString("poster", ""));
                    detail.put("release_date", json.optString("release_date", ""));
                    detail.put("global_id", json.optString("global_id", ""));
                    if (StringUtil.isNotBlank(json.optString("sport_id"))) {
                        detail.put("sport_id", json.optString("sport_id"));
                        detail.put("jump_type", 3);
                    }
                    if (StringUtil.isNotBlank(json.optString("vtype_flag"))) {
                        detail.put("vtype_flag", json.optString("vtype_flag"));
                    }

                }
                idsMap.put(json.optString("global_id", "0"), detail);
            }
        } catch (Exception e) {
            log.error("parse " + url + " error", e);
        }

        return idsMap;
    }

    private static Map<String, Object> getPlayCount(String type, String ids) {
        Map<String, Object> idsMap = new HashMap<>();
        String url = "http://127.0.0.1/vplay/getIdsInfo?type=" + type + "&ids=" + ids;
        JSONArray jArray;
        try {
            jArray = JSONArray.fromObject(HttpToolkit.sendGet(url, 100, 1000));
            System.out.println("get" + url + "=" + jArray.toString());
            log.debug("get" + url + "=" + jArray.toString());
            if (jArray.size() > 0) {
                String commCount = "";
                if (type.equals("vlist")) {
                    commCount = "vcomm_count";
                } else if (type.equals("plist")) {
                    commCount = "pcomm_count";
                }

                for (int i = 0; i < jArray.size(); i++) {
                    JSONObject json = jArray.optJSONObject(i);
                    Map<String, Object> countMap = new HashMap<>();
                    countMap.put("play_count", json.opt("play_count"));
                    countMap.put("comm_count", json.opt(commCount));
                    idsMap.put(json.optString("id"), countMap);
                }
            }
        } catch (Exception e) {
            log.error("parse " + url + " error", e);
        }

        return idsMap;
    }

    //首页瀑布流
    public static List<Map<String, Object>> getRecList(JSONObject json, String versiontype, boolean notAuto) {
        List<Map<String, Object>> recList = new ArrayList<>();
        if (!json.containsKey("rec")) {
            log.warn("rec data not contains rec items!");
            return recList;
        }

        StringBuffer pidsStr = new StringBuffer();
        StringBuffer vidsStr = new StringBuffer();
        StringBuffer pgcIdStr = new StringBuffer();
        JSONArray recArray = json.getJSONArray("rec");
        for (int i = 0; i < recArray.size(); i++) {
            JSONObject rec = recArray.getJSONObject(i);

            Map<String, Object> recMap = new HashMap<>();

            String type = rec.getString("type");
            recMap.put("type", type);
            recMap.put("key", rec.containsKey("key") ? rec.getString("key") : "");

            JSONArray dislikeArray = new JSONArray();
            String dislike = rec.optString("dislike_options");
            try {
                dislikeArray = JSONArray.fromObject(dislike);
            } catch (Exception ignored) {

            }
            recMap.put("dislike_options", dislikeArray);
            recMap.put("serverTime", new Date().getTime());
            switch (type) {
                case "wv": {    //点播
                    JSONObject data = getLBRec(rec.optJSONObject("data"), versiontype, notAuto);
                    recMap.put("data", data);
                    recList.add(recMap);

                    //get ids
                    appendIds(data, pidsStr, vidsStr, pgcIdStr);

                    break;
                }
                case "live":     //直播
                    recMap.put("data", getLiveRec(rec.optJSONObject("data")));
                    recList.add(recMap);
                    break;
                case "live2":     //直播
                    recMap.put("data", getLive2Rec(rec.optJSONObject("data")));
                    recList.add(recMap);
                    break;
                case "zt": {    //专题
                    JSONObject data = rec.optJSONObject("data");
                    recMap.put("data", data);
                    recList.add(recMap);

                    //get ids
//				appendIds(data,pidsStr,vidsStr);
                    break;
                }
                default:
                    log.warn("异常数据,type=" + type + "," + rec.toString());
                    break;
            }
        }
        //并行处理播放数评论数、pgc
        List<Map<String, Object>> list = AsyncExecutors.execAll(asynHandlePlayCommentPgcCount(pidsStr.toString(), vidsStr.toString(), pgcIdStr.toString()));

        if (list != null && list.size() == 3) {
            getPlayCntAndCommCnt(recList, list, versiontype);
        }
        return recList;
    }

    private static List<Callable<Map<String, Object>>> asynHandlePlayCommentPgcCount(final String pidsStr, final String vidsStr, final String pgcIdStr) {
        List<Callable<Map<String, Object>>> list = Lists.newArrayList();

        list.add(() -> getIdsMap(pidsStr, "plist"));

        list.add(() -> getIdsMap(vidsStr, "vlist"));

        list.add(() -> getPgcIdsMap(pgcIdStr));

        return list;

    }

    private static void appendIds(JSONObject data, StringBuffer pidsStr, StringBuffer vidsStr, StringBuffer pgcsStr) {
        if (data.containsKey("id")) {
            String id = data.optString("id");//格式1_10017383
            if (id.length() > 2) {
                if (id.startsWith("1_")) {
                    pidsStr.append(id.substring(2, id.length())).append(",");
                } else if (id.startsWith("4_")) {
                    vidsStr.append(id.substring(2, id.length())).append(",");
                } else {
                    vidsStr.append(id).append(",");
                }
            }
        }

        if (pgcsStr != null && data.optBoolean("is_pgc")) {
            String id = data.optString("pgc_user_id");
            if (StringUtil.isNotBlank(id))
                pgcsStr.append(id).append(",");
        }
    }

    private static Map<String, Object> getIdsMap(String idsStr, String type) {
        Map<String, Object> idsMap = new HashMap<>();
        if (idsStr.length() > 1) {
            idsMap = getPlayCount(type, idsStr);
        }
        return idsMap;
    }

    private static Map<String, Object> getPgcIdsMap(String idsStr) {
        Map<String, Object> idsMap = new HashMap<>();
        if (idsStr.length() > 1) {
            idsMap = getPGCUsers(idsStr);
        }
        return idsMap;
    }


    private static void getPlayCntAndCommCnt(List<Map<String, Object>> recList, List<Map<String, Object>> idsMap, String versionType) {
        recList.stream().filter(rec -> rec.containsKey("data")).forEach(rec -> {
            JSONObject data = (JSONObject) rec.get("data");
            putPlayCntAndCommCnt(data, idsMap, versionType);
        });
    }

    private static void putPlayCntAndCommCnt(JSONObject data, List<Map<String, Object>> idsMap, String versionType) {
        try {

            Map<String, Object> pidsMap = idsMap.get(0);
            Map<String, Object> vidsMap = idsMap.get(1);
            Map<String, Object> pgcsMap = idsMap.get(2);

            if (data.containsKey("id")) {
                Map<String, Object> cntMap = new HashMap<>();
                String id = data.getString("id");
                String[] idArray = id.split("_");
                if ("1".equals(idArray[0])) {
                    if (pidsMap.containsKey(idArray[1])) {
                        cntMap = (Map<String, Object>) pidsMap.get(idArray[1]);
                    }

                } else if ("4".equals(idArray[0])) {
                    if (vidsMap.containsKey(idArray[1])) {
                        cntMap = (Map<String, Object>) vidsMap.get(idArray[1]);
                    }
                } else {
                    if (vidsMap.containsKey(id)) {
                        cntMap = (Map<String, Object>) vidsMap.get(id);
                    }
                }
                if ("LeJianNews".equals(versionType)) {
                    data.put("comm_count", cntMap.get("comm_count"));
                    data.put("commentsCount", cntMap.get("comm_count"));
                } else {
                    data.put("play_count", cntMap.get("play_count"));
                    data.put("comm_count", cntMap.get("comm_count"));
                }

            }
            if (pgcsMap != null && pgcsMap.size() > 0) {
                //大号需求
                if (data.optBoolean("is_pgc")) {
                    String user_id = data.optString("pgc_user_id");
                    if (StringUtils.isNotBlank(user_id)) {
                        JSONObject user = (JSONObject) pgcsMap.get(user_id);
                        if (user != null) {
                            data.put("nickName", user.optString("nickName"));
                            data.put("userName", user.optString("userName"));
                            data.put("picture", user.optString("picture"));
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("process play_count or comm_count error!", e);
        }
    }

    /**
     * 资讯版-视频版
     */
    public static List<Map<String, Object>> getRecOfInfoList(JSONObject json, String versiontype, boolean notAuto) {
        List<Map<String, Object>> recList = new ArrayList<>();
        if (!json.containsKey("rec")) {
            log.warn("rec data not contains rec items!");
            return recList;
        }
        JSONArray recArray = json.getJSONArray("rec");
        StringBuffer pidsStr = new StringBuffer();
        StringBuffer vidsStr = new StringBuffer();
        StringBuffer pgcIdStr = new StringBuffer();
        for (int i = 0; i < recArray.size(); i++) {
            JSONObject rec = recArray.getJSONObject(i);

            Map<String, Object> recMap = new HashMap<>();

            String type = rec.getString("type");
            recMap.put("type", type);
            recMap.put("key", rec.containsKey("key") ? rec.getString("key") : "");
            recMap.put("serverTime", new Date().getTime());
            switch (type) {
                case "wv":
                case "short":     //点播
                    JSONObject data = getLBRec(rec.getJSONObject("data"), versiontype, notAuto);
                    recMap.put("data", data);
                    //get ids
                    appendIds(data, pidsStr, vidsStr, pgcIdStr);

                    recList.add(recMap);
                    break;
                case "live":     //直播
                    recMap.put("data", getLiveRec(rec.getJSONObject("data")));
                    recList.add(recMap);
                    break;
                case "live2":     //直播
                    recMap.put("data", getLive2Rec(rec.getJSONObject("data")));
                    recList.add(recMap);
                    break;
                case "zt":     //专题
                    recMap.put("data", rec.optJSONObject("data"));
                    recList.add(recMap);
                    break;
                default:
                    log.warn("异常数据:" + rec.toString());
                    break;
            }
        }

        List<Map<String, Object>> list = AsyncExecutors.execAll(asynHandlePlayCommentPgcCount(pidsStr.toString(), vidsStr.toString(), pgcIdStr.toString()));

        if (list != null && list.size() == 3) {
            getPlayCntAndCommCnt(recList, list, versiontype);
        }
        return recList;
    }

    //日期格式转换 - 20150323转为2015-03-23
    private static String formatDate(String date, boolean isEnd) {
        String fDate = "";
        if (StringUtil.isBlank(date) || "0".equals(date))
            return fDate;
        if (!isEnd && 8 == date.length()) {
            fDate = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8) + "期 ";
        } else if (8 == date.length()) {
            fDate = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8) + "期 ";
        } else {
            if (isEnd) {
                fDate = "" + date + "集全";
            } else {
                fDate = "第" + date + "集";
            }
        }
        return fDate;
    }

    //获取码率对应的清晰度
    private static String getCodeRate(String codeRate) {
        if (StringUtils.isBlank(codeRate)) {
            return "";
        }
        StringBuilder cb = new StringBuilder();
        String[] crArray = codeRate.split(",");
        label:
        for (String cr : crArray) {
            if (StringUtils.isNotBlank(cr)) {
                String rate = Mappings.CR_MAP.get(cr);
                if (StringUtils.isNotBlank(rate)) {
                    switch (rate) {
                        case "mp4_4k_m_h265":
                        case "mp4_4k_db":
                        case "mp4_4k_dts":
                            cb.append("4k,");
                            break label;
                        case "mp4_720p_3d":
                        case "mp4_1080p_3d":
                            cb.append("3D,");
                            break;
                        case "mp4_800_db":
                        case "mp4_1300_db":
                        case "mp4_720p_db":
                        case "mp4_800_dts":
                        case "mp4_1300_dts":
                        case "mp4_720_dts":
                        case "mp4_1080p3m_dts":
                        case "mp4_2k_db":
                        case "mp4_2k_dts":
                            cb.append("theatre,");
                            break;
                        case "mp4_2k_h265":
                            cb.append("2k,");
                            break;
                        case "mp4_1080p3m":
                            cb.append("1080p,");
                            break;
                    }
                }
            }
        }

        String df = cb.toString();
        if (df.contains("4k")) {
            return "4k";
        } else if (df.contains("3D")) {
            return "3D";
        } else if (df.contains("theatre")) {
            return "theatre";
        } else if (df.contains("2k")) {
            return "2k";
        } else if (df.contains("1080p")) {
            return "1080p";
        } else {
            return "";
        }
    }

    //首页瀑布流 - 点播内容
    private static JSONObject getLBRec(JSONObject wv, String versiontype, boolean notAuto) {
        String category = wv.optString("category", "");

        String src = wv.optString("src", "");
        //different category different view
        JSONArray array = new JSONArray();
        String value;
        //1.站内 2.站外
        if ("1".equals(src)) {
            if ("1".equals(category)) {//电影
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = "电影   " + (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);

            } else if ("2".equals(category)) {//电视剧

                JSONObject json = new JSONObject();
                json.put("label", "");
                value = "电视剧   " + (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("11".equals(category)) {//zongyi

                JSONObject json = new JSONObject();
                json.put("label", "");
                value = "综艺   " + (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);

            } else if ("3".equals(category)) {//娱乐
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("area") ? wv.getString("area") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);

            } else if ("4".equals(category)) {//体育
                if (StringUtil.isNotBlank(wv.optString("sport_id"))) {
                    wv.put("jumpType", 3);
                }
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "") + "  " + (wv.containsKey("style") ? wv.getString("style") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("9".equals(category)) {//音乐
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("area") ? wv.getString("area") : "") + "  " + (wv.containsKey("style") ? wv.getString("style") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("14".equals(category) || "20".equals(category) || "30".equals(category)) {//汽车 风尚 热点
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = wv.containsKey("style") ? wv.getString("style") : "";
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("16".equals(category)) {//纪录片
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("area") ? wv.getString("area") : "") + "  " + (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("22".equals(category)) {//财经
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("23".equals(category)) {//旅游

                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("style") ? wv.getString("style") : "") + "  " + (wv.containsKey("sub_category_name") ? wv.getString("sub_category_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            } else if ("34".equals(category)) {//亲子
                JSONObject json = new JSONObject();
                json.put("label", "");
                value = (wv.containsKey("content_rating") ? wv.getString("content_rating") : "") + "  " + (wv.containsKey("language") ? wv.getString("language") : "") + "  " + (wv.containsKey("video_type_name") ? wv.getString("video_type_name") : "");
                json.put("value", cleanData(value));
                array.add(0, json);
            }
        }


        if ("2".equals(src)) {
            JSONObject json = new JSONObject();
            json.put("label", "");

            String displayName = wv.containsKey("display_category") ? wv.getString("display_category") : "";
            if (!StringUtils.isBlank(displayName)) {
                json.put("value", displayName);
            } else {
                value = (wv.containsKey("category_name") ? wv.getString("category_name") : "") + " " + (wv.containsKey("tag") ? wv.getString("tag") : "");
                json.put("value", cleanData(cutData(cleanData(value), 3)));
            }

            array.add(0, json);

        }
        //handle paly_count
        String globalId = wv.optString("global_id");
        if (StringUtils.isNotBlank(globalId)) {
            globalId = globalId.length() > 4 ? globalId.substring(globalId.length() - 4) : globalId;
            int tmp = NumberUtils.toInt(globalId) % 2000 + 3001; //3001-5000
            String playCount = wv.optString("play_count");
            if (StringUtils.isNotBlank(playCount)) {
                wv.put("play_count", NumberUtils.toInt(playCount) + tmp);
            }
        }


        wv.put("content", array);
        String isend = wv.containsKey("isend") ? wv.getString("isend") : "";

        getPoster(wv);

        if ("LeJianMovie".equals(versiontype) && notAuto) {
            String category_name = wv.optString("category_name");
            String name = wv.containsKey("name") ? wv.optString("name") : "";
            if (wv.optBoolean("is_pgc")) {
                int duration = wv.optInt("duration", -1);
                if (duration > 0 && duration < 15 * 60) {
                    int minute = duration / 60;
                    int second = duration % 60;
                    name += " | " + String.format("%02d", minute) + "'" + String.format("%02d", second) + "''";
                }
            } else if (StringUtil.isNotBlank(category_name) && "电视剧,动漫".contains(category_name)) { //2电视剧和5动漫
                if (!StringUtils.isBlank(name)) {
                    name = name + " | ";
                }
                String videoEpisode = wv.optString("video_episode", "");
                String episodes = wv.optString("episodes");
                if ("0".equals(isend) && StringUtil.isNotBlank(videoEpisode) && !"0".equals(videoEpisode)) {
                    name = name + "第" + videoEpisode + "集";
                } else if ("1".equals(isend) && StringUtil.isNotBlank(episodes) && !"0".equals(episodes)) {
                    name = name + episodes + "集全";
                }
            } else if (StringUtil.isNotBlank(category_name) && "纪录片,综艺".contains(category_name)) { //16纪录片和11综艺
                if (!StringUtils.isBlank(name)) {
                    name = name + " | ";
                }
                String videoEpisode = wv.optString("video_episode", "");
                String episodes = wv.optString("episodes", "");
                if ("1".equals(isend)) {
                    name = name + formatDate(episodes, true);
                } else {
                    name = name + formatDate(videoEpisode, false);
                }
            } else if (StringUtil.isNotBlank(category_name) && "电影".contains(category_name)) { //电影
                if (!StringUtils.isBlank(name)) {
                    name = name + " | ";
                }
                String tmp = wv.optString("release_date");
                if (StringUtil.isNotBlank(tmp) && tmp.length() > 10) {
                    name += tmp.substring(0, 4) + "年";
                }
                tmp = wv.optString("score", "");
                if (StringUtil.isNotBlank(tmp) && !"0".equals(tmp)) {
                    name += " | " + tmp + "分";
                }
            } else { //时长小于15分钟短视频
                int duration = wv.optInt("duration", -1);
                if (duration > 0 && duration < 15 * 60) {
                    int minute = duration / 60;
                    int second = duration % 60;
                    name += " | " + String.format("%02d", minute) + "'" + String.format("%02d", second) + "''";
                }

            }

            wv.put("name", StringEscapeUtils.unescapeHtml4(name));
        }

        String codeRate = wv.containsKey("code_rate") ? wv.getString("code_rate") : "";
        wv.put("code_rate", getCodeRate(codeRate));

        return wv;
    }

    /**
     * 获取PGC大号昵称
     *
     * @param userId 大号id
     * @return 大号昵称
     */
    public static JSONObject getPGCUser(String userId) {
        JSONObject user = new JSONObject();
        //获取大号昵称
        if (StringUtils.isBlank(userId))
            return user;

        JSONObject userJson = JSONObject.fromObject(HttpToolkit.sendGet("http://127.0.0.1/api/getUserByID/uid/" + userId));
        if (!userJson.isNullObject() && !userJson.isEmpty()) {
            Integer ret = userJson.optInt("status");
            if (1 == ret) {
                JSONObject data = userJson.optJSONObject("bean");
                String pic = data.optString("picture");
                if (StringUtil.isNotBlank(pic) && pic.contains(",")) {
                    pic = pic.split(",")[0];
                }
                user.put("nickName", data.optString("nickname"));
                user.put("picture", pic);
            }
        }
        return user;
    }

    /**
     * 批量获取PGC大号昵称
     *
     * @param userIds 大号id list
     * @return 大号昵称
     */
    private static Map<String, Object> getPGCUsers(String userIds) {
        Map<String, Object> user = new HashMap<>();
        //获取大号昵称
        if (StringUtils.isBlank(userIds))
            return user;

        JSONObject userJsons = JSONObject.fromObject(HttpToolkit.sendGet("http://127.0.0.1/api/getUserByIdList?uidlist=" + userIds));
        if (!userJsons.isNullObject() && !userJsons.isEmpty()) {
            Integer ret = userJsons.optInt("status");
            if (1 == ret) {
                JSONArray datas = userJsons.optJSONArray("bean");
                if (datas != null && datas.size() > 0) {
                    for (int i = 0; i < datas.size(); i++) {
                        JSONObject tmp = datas.optJSONObject(i);
                        String uid = tmp.optString("uid");
                        String pic = tmp.optString("picture");
                        String nickName = tmp.optString("nickname");
                        String userName = tmp.optString("username");
                        if (StringUtil.isNotBlank(pic) && pic.contains(",")) {
                            pic = pic.split(",")[0];
                        }
                        tmp.clear();
                        tmp.put("nickName", nickName);
                        tmp.put("userName", userName);
                        tmp.put("picture", pic);
                        user.put(uid, tmp);
                    }

                }
            }
        }
        return user;
    }

    private static String cleanData(String value) {
        String result = "";
        if (StringUtils.isNotBlank(value)) {
            result = value.replaceAll("其他", "").replaceAll("正片", "").replaceAll("全部", "").replaceAll("频道", "").replaceAll("null", "").replaceAll(",", "  ");
        }
        return result;

    }

    private static String cutData(String value, int len) {
        StringBuilder sb = new StringBuilder();
        List<String> list = new ArrayList<>();

        try {
            if (!StringUtils.isBlank(value)) {

                String[] tags = value.split("\\s+");
                for (String tag1 : tags) {
                    if (StringUtils.isNotBlank(tag1)) {
                        if (!list.contains(tag1)) {
                            list.add(list.size(), tag1);
                        }

                        if (list.size() >= len) {
                            break;
                        }
                    }
                }

                for (String tag : list) {
                    sb.append(tag).append(" ");
                }

            }
        } catch (Exception e) {
            log.warn("cutdata error!");
            return "";
        }

        return sb.toString();
    }

    private static String cutData(String value) {
        String result = "";
        StringBuilder sb = new StringBuilder();

        String[] tags = value.split(";");
        int limit = 2;
        if (tags.length > 3) {
            for (int i = 0; i < tags.length; i++) {
                if (StringUtils.isNotBlank(tags[i])) {
                    sb.append(tags[i]);
                    if (i >= limit) {
                        result = sb.toString();
                        break;
                    }
                    sb.append(";");
                } else {
                    limit += 1;
                }
            }
        } else {
            result = value;
        }

        return result;

    }

    private static void getPoster(JSONObject wv) {

        if (wv.containsKey("poster")) {
            Object obj = wv.get("poster");
            if (JSONUtils.isString(obj)) {
                wv.put("poster", obj);
            } else {
                processPosterObj(wv, obj);
            }
        } else {
            log.warn("wv not containsKey poster.");
        }

    }

    private static void processPosterObj(JSONObject wv, Object obj) {

        JSONObject json = (JSONObject) obj;
        String src = wv.containsKey("src") ? wv.optString("src") : "";
        if ("1".equals(src)) {
            processLetvPosterObj(wv, json);
        } else if ("2".equals(src)) {
            wv.put("poster", json.optString("default"));
        }
        log.info("poster:" + wv.get("poster"));
    }

    private static void processLetvPosterObj(JSONObject wv, JSONObject json) {
        String poster = "";
        boolean isBig = wv.containsKey("is_big_pic") && wv.getBoolean("is_big_pic");
        //大圖
        if (isBig) {
            poster = json.containsKey("1440*810") ? json.optString("1440*810") : "";
            if (StringUtils.isBlank(poster)) {
                poster = json.containsKey("1080*608") ? json.optString("1080*608") : "";
            }
            if (StringUtils.isBlank(poster)) {
                poster = json.containsKey("960*540") ? json.optString("960*540") : "";
            }

        } else {
            //小圖
            if (StringUtils.isBlank(poster)) {
                poster = json.containsKey("400*225") ? json.getString("400*225") : "";
            }
            if (StringUtils.isBlank(poster)) {
                poster = json.containsKey("320*200") ? json.getString("320*200") : "";
            }
            if (StringUtils.isBlank(poster)) {
                poster = json.containsKey("200*150") ? json.getString("200*150") : "";
            }
            if (StringUtils.isBlank(poster)) {
                poster = json.containsKey("180*135") ? json.getString("180*135") : "";
            }
        }
        if (StringUtils.isBlank(poster)) {
            poster = json.optString("default");
        }
        wv.put("poster", poster);
    }


    //首页瀑布流 - 直播内容
    private static Map<String, Object> getLiveRec(JSONObject live) {
        Map<String, Object> liveMap = new HashMap<>();

        liveMap.put("beginTime", live.containsKey("beginTime") ? live.getString("beginTime") : "");
        liveMap.put("ch", live.containsKey("ch") ? live.getString("ch") : "");
        liveMap.put("channelClass", live.containsKey("channelClass") ? live.getString("channelClass") : "");
        liveMap.put("channelEname", live.containsKey("channelEname") ? live.getString("channelEname") : "");
        if (live.containsKey("channelId")) {
            liveMap.put("channelId", live.getInt("channelId"));
        }
        liveMap.put("channelName", live.containsKey("channelName") ? live.getString("channelName") : "");
        if (live.containsKey("childLock")) {
            liveMap.put("childLock", live.getInt("childLock"));
        }
        liveMap.put("cibnChannelName", live.containsKey("cibnChannelName") ? live.getString("cibnChannelName") : "");
        liveMap.put("cibnWatermarkUrl", live.containsKey("cibnWatermarkUrl") ? live.getString("cibnWatermarkUrl") : "");
        liveMap.put("demandId", live.containsKey("demandId") ? live.getString("demandId") : "");
        liveMap.put("is3D", live.containsKey("is3D") ? live.getString("is3D") : "");
        liveMap.put("is4K", live.containsKey("is4K") ? live.getString("is4K") : "");
        liveMap.put("isRecommend", live.containsKey("isRecommend") ? live.getString("isRecommend") : "");
        liveMap.put("numericKeys", live.containsKey("numericKeys") ? live.getString("numericKeys") : "");
        liveMap.put("orderNo", live.containsKey("orderNo") ? live.getString("orderNo") : "");
        liveMap.put("pcWatermarkUrl", live.containsKey("pcWatermarkUrl") ? live.getString("pcWatermarkUrl") : "");
        liveMap.put("postH3", live.containsKey("postH3") ? live.getString("postH3") : "");
        liveMap.put("postOrigin", live.containsKey("postOrigin") ? live.getString("postOrigin") : "");
        liveMap.put("postS1", live.containsKey("postS1") ? live.getString("postS1") : "");
        liveMap.put("postS2", live.containsKey("postS2") ? live.getString("postS2") : "");
        liveMap.put("postS3", live.containsKey("postS3") ? live.getString("postS3") : "");
        liveMap.put("postS4", live.containsKey("postS4") ? live.getString("postS4") : "");
        liveMap.put("postS5", live.containsKey("postS5") ? live.getString("postS5") : "");
        liveMap.put("sourceId", live.containsKey("sourceId") ? live.getString("sourceId") : "");
        liveMap.put("watermarkUrl", live.containsKey("watermarkUrl") ? live.getString("watermarkUrl") : "");

        liveMap.put("cur", live.containsKey("cur") ? live.getJSONObject("cur") : new HashMap<String, Object>());
        liveMap.put("streams", live.containsKey("streams") ? live.getJSONArray("streams") : new ArrayList<Map<String, Object>>());

        String codeRate = live.containsKey("code_rate") ? live.getString("code_rate") : "";
        liveMap.put("code_rate", getCodeRate(codeRate));

        return liveMap;
    }


    //首页瀑布流 - 直播内容
    private static JSONObject getLive2Rec(JSONObject live) {
        //解析逻辑后续如有需求变动再这里修改
        return live;
    }
}